#include "Comm.h"
#include "string.h"
 

void Comm::GameInitializer(void* threadParams) {
	Sleep(1000);
	portIPSim* args = (portIPSim*)threadParams;
	char Buffer[10];
	cout << "Server Sender Started on: " + args->ipAddress + "Port: " + itoa(args->port,Buffer, 10) << endl;
	try {
		
		static SocketServer* s = new SocketServer(args->port, 10, BlockingSocket);
		//const char* info;	
		Socket* client = s->Accept();
		//get a pointer to the simulation
		Sim* tempSim = args->gameSim;
		string temp = "";
		//send orbital bodies
		for(int i = 0; i < tempSim->getNumOrbitalBodies(); i++) {

			GravBody* shit = tempSim->getOrbitalBody(i);
			//send out the initial states of the GravBodies
			//only need to send at beginning, so outside of loop
			//we send the commamd ID, gravBody ID, x pos, y pos, z pos,
			//radius, and mass.			
			temp += Utils::ftoa(INIT_ORBITAL_BODY);	//the command
			temp += ",";
			temp += Utils::ftoa(shit->getID()) ;  //the GravBody's ID
			temp += ",";
			const Vec3f* tloc = shit->getLoc();
			temp += Utils::ftoa(tloc->x);		//the x location
			temp += ",";
			temp += Utils::ftoa(tloc->y);		//the y location
			temp += ",";
			temp += Utils::ftoa(tloc->z);		//the z location
			temp += ",";
			temp += Utils::ftoa(shit->getMass());//the mass
			temp += ",";
			temp += Utils::ftoa(shit->getRad()); //the radius
			temp += ",";
		}

		for(int i = 0; i < tempSim->getNumDebrisBodies(); i++) {
			GravBody* shit = tempSim->getDebrisBody(i);
			//send out the initial states of the GravBodies
			//only need to send at beginning, so outside of loop
			//we send the commamd ID, gravBody ID, x pos, y pos, z pos,
			//radius, and mass.	
			temp += Utils::ftoa(INIT_DEBRIS_BODY);	//the command
			temp += ",";
			temp += Utils::ftoa(shit->getID());		//the GravBody's ID
			temp += ",";
			const Vec3f* tloc = shit->getLoc();
			temp += Utils::ftoa(tloc->x);			//the x location
			temp += ",";
			temp += Utils::ftoa(tloc->y);			//the y location
			temp += ",";
			temp += Utils::ftoa(tloc->z);			//the z location
			temp += ",";
			temp += Utils::ftoa(shit->getMass());	//the mass
			temp += ",";
			temp += Utils::ftoa(shit->getRad());		//the radius
			temp += ",";
		}

		//set the sim as being ready
		temp += Utils::ftoa(CLIENT_SIM_START);
		temp += ",";
		//send out ready signal
		client->SendLine(temp);
		temp.clear();
		
		//Add our socket to the static list
		for(int i = 0; i < 8;i++)
		{
			if(socketArray[i] == NULL)
			{
				socketArray[i] = s;
			}
		}
	}
	catch ( string str ) { cerr << "ServerSender was bad: " << str << endl; }
	catch ( ... ) { cerr << "unhandled exception\n"; }
}